package com.xcjw.com.Utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xcjw.com.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**

 */
public class Utils {
    private static long lastClickTime;
    private static Transformation transformation;

    /**
     * @return 防止按钮重复点击
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    /**
     * @param
     */
    public static void disabledView(final View v) {
        v.setClickable(false);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                v.setClickable(true);
            }
        }, 1500);
    }

    /*设置按钮什么时候可以点击*/
    public static void disabledView(final View v, long delayMillis) {
        v.setEnabled(false);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                v.setEnabled(true);
            }
        }, delayMillis);
    }

    public static boolean isAccount(String telphone) {
        try {
            // 用户名
            Pattern p = Pattern.compile("^[a-z,A-Z][a-zA-Z0-9_]{3,11}$"); //
            // 验证用户名
            Matcher m = p.matcher(telphone);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isElectronicMail(String telphone) {
        try {
            // 电子邮箱
            // Pattern p = Pattern
            // .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
            // //
            Pattern p = Pattern
                    .compile("^[A-Za-z0-9][\\w\\._]*[a-zA-Z0-9]+@[A-Za-z0-9-_]+\\.([A-Za-z]{2,4})");
            // 验证电子邮箱
            Matcher m = p.matcher(telphone);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isNumber(String telphone) {
        try {
            // 数字
            // Pattern p = Pattern
            // .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
            // //
            Pattern p = Pattern
                      .compile("^[0-9]*$");
            // 验证电子邮箱
            Matcher m = p.matcher(telphone);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isLicenseNumber(String licenseNumber) {
        try {
            // 车牌号
            Pattern p = Pattern
                    .compile("^[\u4e00-\u9fa5][A-Z][-.]?[A-Z0-9]{5}"); //
            Matcher m = p.matcher(licenseNumber);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean isUser(String licenseNumber) {
        try {
            // 车牌号
            Pattern p = Pattern
                      .compile("^[J][Y][D][C][.][U][s][e]]"); //
            Matcher m = p.matcher(licenseNumber);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean isGroup(String licenseNumber) {
        try {
            // 车牌号
            Pattern p = Pattern
                      .compile("^[\u4e00-\u9fa5][A-Z][-.]?[A-Z0-9]{5}"); //
            Matcher m = p.matcher(licenseNumber);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isChineseCharacters(String str) {
        try {
            Pattern p = Pattern.compile("^[\u4e00-\u9fa5]"); //
            Matcher m = p.matcher(str);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isSize(String str) {
        try {
            String pattern = "^([1-9][0-9]?|0)(\\.([0-9]$))?$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    /*对成功后的身份证号后八位密文处理*/
    public static String MakeCardID(String s) {
        String s1 = s.substring(0, 6);
        String s2 = s.substring(s.length() - 4, s.length());
        return s1 + "*******"+s2;
    } /*对成功后的身份证号后八位密文处理*/
    public static String makephone(String s) {

        String s3 = s.substring(4, s.length() - 4);
        String s1 = s.substring(0, 3);
        String s2 = s.substring(s.length()-4,s.length());
        return s1 + "****"+s2;
    }

    public static boolean isName(String name) {
        try {
            Pattern p = Pattern.compile("/[\\u4E00-\\u9FA5]{2,5}(?:·[\\u4E00-\\u9FA5]{2,5})*/"); //
            Matcher m = p.matcher(name);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean isFixationNumber(String fixation) {
        try {
            // 固定电话
            Pattern p = Pattern.compile("^(^0\\d{2}-?\\d{8}$)|(^0\\d{3}-?\\d{7}$)|(^\\(0\\d{2}\\)-?\\d{8}$)|(^\\(0\\d{3}\\)-?\\d{7}$)$"); // 验证固定电话
            Matcher m = p.matcher(fixation);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isPhone(String telphone) {
        try {
            // 手机号码
            Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15([0-9]))|(16([6]))|(17[0-9])|(18[0-9])|(19([7-9])))\\d{8}$"); //  验证手机号 首位为1 第二位为3,4,5,7,8，为9位数字
            //Pattern p = Pattern.compile("^[1][0-9]{10}$"); // 验证手机号
            Matcher m = p.matcher(telphone);
            return m.matches();
        } catch (Exception e) {
            return false;
        }

    }

    public static boolean isPassword(String password) {
        try {
            // 密码由字母、数字、下划线组成
            if (password != null) {
                Pattern regexpwd = Pattern
                        .compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,18}$");
                Matcher m = regexpwd.matcher(password);
                return m.matches();
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }


    //科学计数法
    public static String TransformData(Double price) {
        String xprice = String.valueOf(price);
        BigDecimal db = new BigDecimal(xprice);
        String ii = db.toPlainString();
        return ii;
    }

    public static String TransformData(String price) {
        BigDecimal db = new BigDecimal(price);
        return db.toPlainString();
    }

    /**
     * 对数据进行".0"判断处理
     *
     * @param
     * @return
     */
    public static String DisposeData(Object o) {
        String str = String.valueOf(o);
        if (str.trim().endsWith(".0")) {
            return str.split("\\.")[0];
        } else {
            return str;
        }
    }

    /**
     * 对数据进行科学计数法和".00"判断处理
     *
     * @param
     * @return
     */
    public static String DisposeDataTwo(Object o) {
        String str = String.valueOf(new DecimalFormat("0.00").format(o));
        if (str.trim().endsWith(".00")) {
            return str.split("\\.")[0];
        } else {
            return str;
        }
    }

    // 判断运输报价是否符合规范0.1-99999999.9
    public static boolean isShippingCharge(String str) {
        try {
            if ("0.0".equals(str)) {
                return false;
            }
            String pattern = "^(?!0$)([1-9][0-9]{0,7}|0)(\\.[0-9]{0,1})?$";
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    // 拨打电话
    public static void makeCall(Context context, String number) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + number));
        context.startActivity(intent);
    }

    public static String deletehaha(String str) {
        if (str.indexOf("+86") != -1) {
            return str.replace("+86", "");
        } else if (str.indexOf("-") != -1) {
            return str.replace("-", "");
        } else if (str.indexOf(" ") != -1) {
            return str.replace(" ", "");
        }

        return str;

    }

    /**
     * @return 验证有没有输入内容
     */
    public static boolean verifyCorrectPrint(Context mContext, EditText et, int rsd) {
        if (et != null) {
            if (et.getText().toString().isEmpty()) {
                ToastUtils.shorttoast(mContext, "请输入内容");
                return false;
            }
        }
        return true;
    }

    //判断是否是身份证号
    public static boolean isCardID(String str) {
        try {
            if (str.length() == 18) {
                Pattern p = Pattern.compile("^[0-9]{17}[0-9|xX]{1}$");
                Matcher m = p.matcher(str);
                return m.matches();
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


    /*动态添加内容*/
    public static void setTextView(Context context, int content, LinearLayout layout) {
        TextView textView = new TextView(context);
        textView.setText(content);
        textView.setTextColor(context.getResources().getColor(R.color.login_white));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        layout.addView(textView);
    }

    /*动态添加图片*/
    public static void setImgView(Context context, int imageRes, LinearLayout layout) {
        ImageView img = new ImageView(context);
        img.setImageResource(imageRes);
        layout.addView(img);
    }


//设置圆角矩形图片暂时用不着.
   /* public static Transformation getTransformation() {
        if (transformation == null) {
            transformation = new RoundedTransformationBuilder()
                    .borderColor(R.color.border_color)
                    .borderWidthDp(0.3f)
                    .cornerRadiusDp(5)
                    .oval(false)
                    .build();
        }
        return transformation;
    }*/

    /**
     * @param //activity    当前的activity实例
     * @param //currentTime 初始时间
     * @param //oldTime     获取的当前时间
     * @return 拼接的时间字符串
     */
//    public static StringBuilder getCurrent(Context activity, String currentTime, String oldTime) {
//        StringBuilder timerBuilder = MyAdwlFactory.getStringBuilder();
//        try {
//            if (null != currentTime && !"".equals(currentTime)) {
//                Long currenttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(currentTime).getTime();
//                Long publishtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(oldTime).getTime();
//                Long time = (currenttime - publishtime) / 1000;
//                if (time >= 0 && time <= 60 * 30) {
//                    if (time <= 60) {
//                        timerBuilder.append(activity.getResources().getString(R.string.text_just));
//                    } else {
//                        timerBuilder.append(time / 60).append(activity.getResources().getString(R.string.text_minute));
//                    }
//                } else {
//                    String currentString = new SimpleDateFormat("yyyy-MM-dd").format(new Date(currenttime));
//                    String publishString = new SimpleDateFormat("yyyy-MM-dd").format(new Date(publishtime));
//                    int currentDay = Integer.valueOf(currentString.substring(8, 10));
//                    int publishDay = Integer.valueOf(publishString.substring(8, 10));
//
//                    if (currentString.equals(publishString)) {
//                        if (Integer.valueOf(oldTime.substring(11, 13)) < 12) {
//                            timerBuilder.append("上午").append(oldTime.substring(11, 16));
//                        } else {
//                            timerBuilder.append("下午").append(oldTime.substring(11, 16));
//                        }
//                    } else if (currentDay == publishDay + 1) {
//                        //昨天发布
//                        timerBuilder.append("昨天").append(oldTime.substring(11, 16));
//                    } else if (currentDay == publishDay + 2) {
//                        //2天前天发布
//                        timerBuilder.append("前天").append(oldTime.substring(11, 16));
//                    } else if (currentDay == publishDay + 3) {
//                        // 3天前发布
//                        timerBuilder.append(oldTime.substring(5, 16));
//                    } else {
//                        if (currentString.charAt(3) != publishString.charAt(3)) {
//                            timerBuilder.append(oldTime.substring(0, 16));
//                        } else {
//                            timerBuilder.append(oldTime.substring(5, 16));
//                        }
//                    }
//                }
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return timerBuilder;
//    }
    public static DisplayMetrics getScreenWH(Context context) {
        DisplayMetrics dMetrics = new DisplayMetrics();
        dMetrics = context.getResources().getDisplayMetrics();
        return dMetrics;
    }

    /**
     * 计算焦点及测光区域
     *
     * @param focusWidth
     * @param focusHeight
     * @param areaMultiple
     * @param x
     * @param y
     * @param previewleft
     * @param previewRight
     * @param previewTop
     * @param previewBottom
     * @return Rect(left, top, right, bottom) : left、top、right、bottom是以显示区域中心为原点的坐标
     */
    public static Rect calculateTapArea(int focusWidth, int focusHeight,
                                        float areaMultiple, float x, float y, int previewleft,
                                        int previewRight, int previewTop, int previewBottom) {
        int areaWidth = (int) (focusWidth * areaMultiple);
        int areaHeight = (int) (focusHeight * areaMultiple);
        int centerX = (previewleft + previewRight) / 2;
        int centerY = (previewTop + previewBottom) / 2;
        double unitx = ((double) previewRight - (double) previewleft) / 2000;
        double unity = ((double) previewBottom - (double) previewTop) / 2000;
        int left = clamp((int) (((x - areaWidth / 2) - centerX) / unitx),
                -1000, 1000);
        int top = clamp((int) (((y - areaHeight / 2) - centerY) / unity),
                -1000, 1000);
        int right = clamp((int) (left + areaWidth / unitx), -1000, 1000);
        int bottom = clamp((int) (top + areaHeight / unity), -1000, 1000);

        return new Rect(left, top, right, bottom);
    }

    public static int clamp(int x, int min, int max) {
        if (x > max)
            return max;
        if (x < min)
            return min;
        return x;
    }

    /**
     * 检测摄像头设备是否可用
     * Check if this device has a camera
     *
     * @param context
     * @return
     */
    public static boolean checkCameraHardware(Context context) {
        if (context != null && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * bitmap旋转
     *
     * @param b
     * @param degrees
     * @return
     */
    public static Bitmap rotate(Bitmap b, int degrees) {
        if (degrees != 0 && b != null) {
            Matrix m = new Matrix();
            m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
            try {
                Bitmap b2 = Bitmap.createBitmap(
                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
                if (b != b2) {
                    b.recycle();  //Android开发网再次提示Bitmap操作完应该显示的释放
                    b = b2;
                }
            } catch (OutOfMemoryError ex) {
                // Android123建议大家如何出现了内存不足异常，最好return 原始的bitmap对象。.
                return b;
            }
        }
        return b;
    }

    public static final int getHeightInPx(Context context) {
        final int height = context.getResources().getDisplayMetrics().heightPixels;
        return height;
    }

    public static final int getWidthInPx(Context context) {
        final int width = context.getResources().getDisplayMetrics().widthPixels;
        return width;
    }

    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        try {
            Matrix matrix = new Matrix();

            matrix.postRotate(angle);
            System.out.println("angle2=" + angle);
            // 创建新的图片
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            return resizedBitmap;
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 存储图像并将信息添加入媒体数据库
     */
    public static Uri insertImage(ContentResolver cr, String name, long dateTaken,
                                  String directory, String filename, Bitmap source, byte[] jpegData) {
        OutputStream outputStream = null;
        String filePath = directory + filename;
        try {
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(directory, filename);
            if (file.createNewFile()) {
                outputStream = new FileOutputStream(file);
                if (source != null) {
                    source.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                } else {
                    outputStream.write(jpegData);
                }
            }
        } catch (FileNotFoundException e) {
            LogUtil.e("", e.getMessage());
            return null;
        } catch (IOException e) {
            LogUtil.e("", e.getMessage());
            return null;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Throwable t) {
                }
            }
        }
        ContentValues values = new ContentValues(7);
        values.put(MediaStore.Images.Media.TITLE, name);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
        values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATA, filePath);
        return cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    /*
     * 货源；列表显示姓名或公司名称处理
     */
    public static String DealString(String str) {
        if (str.length() > 4) {
            return str.substring(0, 4) + "...";
        }
        return str;
    }
    public static String getDateTimeFromMillisecond(Long millisecond){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }


}